// 引入koa-router
const Router = require('koa2-router');
const router = new Router();

const { timeTrans } = require("../../utils");
const {
  getBanner,
  addBanner,
  updateBanner,
  deleteBanner,
  showBanner,
  batchDelete
} = require("../../model/admin/banner");

/* banner增删改查 */

// 查找banner
router.get("/",async (ctx) => {
  ctx.body = await getBanner();
});

// 添加banner
router.post("/add",async (ctx) => {
  const banner_id = Number(ctx.request.body.banner_id);
  // 排序值去重
  const data = await getBanner();
  let isBannerId = data.some(item=>{
    return item.banner_id === banner_id;
  })
  if (isBannerId){
    ctx.body = {
      code: 500,
      msg: "排序值重复，请重新输入"
    };
  }else {

    const src = "http://localhost/images/home/" + ctx.request.body.src.name;
    const url = "#/product/?id=" + ctx.request.body.product_id;
    const atime = timeTrans(ctx.request.body.atime);
    // console.log(ctx.request);
    // console.log(banner_id,src,url,atime);
    try {
      await addBanner([banner_id, src, url, atime]);
      ctx.body = {
        code: 200,
        msg: "添加轮播成功",
      };
    }catch (err) {
      ctx.body = {
        code: 500,
        msg: "添加轮播失败",
        err,
      };
    }

  }
});

// 修改banner
router.post("/update",async (ctx) => {
  const banner_id = Number(ctx.request.body.banner_id);
  const src = "http://localhost/images/home/" + ctx.request.body.src.name;
  const url = "#/product/?id=" + ctx.request.body.product_id;
  const atime = timeTrans(ctx.request.body.atime);

  try {
    await updateBanner([src, url, atime, banner_id]);
    ctx.body = {
      code: 200,
      msg: "修改轮播成功",
    };
  }catch (err) {
    ctx.body = {
      code: 500,
      msg: "修改轮播失败",
      err,
    };
  }
});

// 删除单个banner
router.get("/delete",async (ctx) => {
  // console.log(req.query);
  const banner_id = Number(ctx.request.query.banner_id);

  try {
    await deleteBanner([banner_id]);
    ctx.body = {
      code: 200,
      msg: "删除轮播成功",
    };
  }catch (err) {
    ctx.body = {
      code: 500,
      msg: "删除轮播失败",
      err,
    };
  }
});

// 是否展示banner
router.get("/show", (ctx) => {
  // console.log(req.query);
  const isShow = ctx.request.query.isShow !== "false";
  const banner_id = Number(ctx.request.query.banner_id);

  try {
    showBanner([isShow, banner_id]);
    ctx.body = {
      code: 200,
      msg: "修改成功",
    };
  }catch (err) {
    ctx.body = {
      code: 500,
      msg: "修改失败",
      err,
    };
  }
});

// 批量删除
router.post("/batchDelete",async (ctx) => {
  const arr = ctx.request.body.arr;
  arr.forEach((item,index,arr)=>{
    arr[index] = Number(item);
  })
  // ctx.body = 'ok'
  try {
    await batchDelete([arr]);
    ctx.body = {
      code:200,
      msg:"删除成功"
    };
  }catch (err) {
    console.log(err);
    ctx.body = {
      code:500,
      msg:"删除失败",
      err
    };
  }

});

module.exports = router;
